package com.keyancompany.zhongbaopingtai.activity;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.keyancompany.zhongbaopingtai.Constants;
import com.keyancompany.zhongbaopingtai.R;
import com.keyancompany.zhongbaopingtai.adapter.CollectionAdapter;
import com.keyancompany.zhongbaopingtai.api.CollectionAPI;
import com.keyancompany.zhongbaopingtai.listener.IAsyncHttpResponseHandler;
import com.keyancompany.zhongbaopingtai.listener.IClickCancleListener;
import com.keyancompany.zhongbaopingtai.model.BaseModel;
import com.keyancompany.zhongbaopingtai.model.EventBusEntity;
import com.keyancompany.zhongbaopingtai.model.FindModel;
import com.keyancompany.zhongbaopingtai.utils.IntentUtils;
import com.keyancompany.zhongbaopingtai.weight.IListView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.Bind;
import butterknife.BindString;
import butterknife.OnItemClick;

/**
 * 我的收藏
 */
public class CollectionActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, IAsyncHttpResponseHandler {

    @BindString(R.string.my_collection_text)
    String title;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.swipe_layout)
    SwipeRefreshLayout swipeLayout;
    @Bind(R.id.list_view)
    IListView listView;
    @Bind(R.id.empty_view)
    LinearLayout emptyView;


    private CollectionAdapter mAdapter;
    private int currentPage = 1;
    private int total = 1;
    private boolean isRefrence = true;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    swipeLayout.setRefreshing(false);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected int getContentViewId() {
        return R.layout.activity_collection;
    }

    @Override
    protected int getMenuId() {
        return 0;
    }

    @Override
    protected void initToolBar() {
        initToolBar(toolbar, title);
    }

    @Override
    protected void setUpViews() {
        EventBus.getDefault().register(this);
        mAdapter = new CollectionAdapter(mContext, new IClickCancleListener() {
            @Override
            public void clickCancle(final int position) {

                CollectionAPI.deleteCollection(mAdapter.getItem(position).getPID_(), new IAsyncHttpResponseHandler() {
                    @Override
                    public void start(int type) {

                    }

                    @Override
                    public void success(int type, String json) {
                        Log.e("collection ", " result " + json);
                        if (validateJson(json) != null) {
                            mAdapter.remove(position);
                        }
                        isEmpty();
                    }

                    @Override
                    public void failed(String error) {

                    }

                    @Override
                    public void finish(int type) {

                    }
                }, getLoading(-1));
            }
        });
        listView.setAdapter(mAdapter);
        listView.setStateListener(new IListView.SwipeLayoutState() {
            @Override
            public boolean isRefresh() {
                return swipeLayout.isRefreshing();
            }

            @Override
            public boolean isLastPage() {
                return total == currentPage;
            }

            @Override
            public void requestNextPage() {
                requestTask(++currentPage);
            }
        });
        swipeLayout.post(new Thread(new Runnable() {

            @Override
            public void run() {
                swipeLayout.setRefreshing(true);
                onRefresh();
            }
        }));
        swipeLayout.setOnRefreshListener(this);

    }

    public void requestTask(int currentPage) {

        CollectionAPI.getCollectionList(currentPage, this, getLoading(-1));
    }

    @OnItemClick(R.id.list_view)
    void itemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position < mAdapter.getCount()) {
//            IntentUtils.startActivity(mContext, ProjectDetailActivity.class, Constants.ITEM, mAdapter.getItem(position));
            Intent intent = new Intent(mContext, ProjectDetailActivity.class);
            intent.putExtra(Constants.ITEM, mAdapter.getItem(position));
            intent.putExtra("res","collection");
            intent.putExtra("position", position);
            startActivity(intent);
        }
    }

    /**
     * 事件订阅者自定义的接收方法
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventBusEntity event) {
//        //（1）将事件发布者发布的数据作为文本修改内容
//        msgFragment.setText(event.data);
        //（2）将事件发布者发布的数据作为方法执行的区分
        switch (event.getType()) {
            case EventBusEntity.Type.COLLECTION:
                mAdapter.replace(event.getPosition(), (FindModel) event.getItem());
                break;
        }
    }

    @Override
    public void success(int type, String json) {
        super.success(type, json);
        mHandler.sendEmptyMessage(1);
        if (isRefrence) {
            mAdapter.clear();
//            mAdapter.addAllAfter();
        }
        listView.loadMoreFinish();
        BaseModel base = validateJson(json);
        if (base != null) {
            JSONObject result = JSON.parseObject(base.data);
            total = result.getInteger(Constants.TOTAL);
            currentPage = result.getInteger(Constants.CURRENT);
            if (total == currentPage)
                listView.removeFooterView();
            List<FindModel> items = JSONArray.parseArray(result.getString(Constants.LIST), FindModel.class);
            mAdapter.addAllAfter(items);
        }
        isEmpty();
    }

    public void isEmpty() {
        if (mAdapter.getCount() < 1) {
            emptyView.setVisibility(View.VISIBLE);
            swipeLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void failed(String error) {
        swipeLayout.setRefreshing(false);
        super.failed(error);
    }

    @Override
    public void onRefresh() {
        currentPage = 1;
        requestTask(currentPage);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
